package com.hongawen.mqtt.controller;

import com.hongawen.mqtt.entity.Topic;
import com.hongawen.mqtt.service.TopicService;
import com.hongawen.mqtt.utils.MqttTemplate;
import lombok.RequiredArgsConstructor;
import org.springframework.integration.endpoint.MessageProducerSupport;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author hongawen
 * @version 1.0.0
 * @date 2021年11月23日 16:18
 */
@RestController
@RequiredArgsConstructor
public class MqttController {


    private final TopicService topicService;

    private final MqttTemplate mqttTemplate;

    @GetMapping("add")
    public String add(String topic) {
        topicService.addTopic(topic);
        return "success";
    }

    @GetMapping("remove")
    public String remove(String topic) {
        topicService.removeTopic(topic);
        return "success";
    }

    @GetMapping("push")
    public String push(String topic, String payload) {
        mqttTemplate.sendToTopic(payload, topic);
        return "success";
    }


    @GetMapping("getAll")
    public List<Topic> getAll() {
        String[] allTopics = topicService.getAllTopics();
        List<Topic> topics = new ArrayList<>();
        Arrays.stream(allTopics).forEach(s -> {
            Topic topic = new Topic();
            topic.setName(s);
            topic.setValue(s);
            topics.add(topic);
        });
        return topics;
    }

}
